/**
 * 
 */
package com.qianhai.manage.web;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.qianhai.manage.service.IWaresService;
import com.qianhai.manage.util.ImageUtil;
import com.qianhai.manage.util.StringUtil;
import com.qianhai.manage.vo.WaresInfo;

/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping("wares")
public class WaresController extends BaseController {
	
	private final static String PATH = "/root/show-web/lib/webapp/static/wx_static/site_media/pics/wares";
//	private final static String PATH = "F:/ActiveXTest/test/wares";
	
	@Resource
	private IWaresService waresService;
	
	@RequestMapping("manage")
	public String waresInit() {
		return "wares/wmanage";
	}
	
	@RequestMapping("editWares")
	public String editWaressInit(String id, ModelMap map) {
		if(!StringUtil.isEmpty(id)) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("id", id);
			WaresInfo vo = this.waresService.queryWares(param);
			map.put("vo", vo);
			String picture = "";
			if(!StringUtil.isEmpty(vo.getPicture1())) {
				picture += vo.getPicture1() + "@@" + this.changeBase64(vo.getPicture1()) + "(X)";
			}
			if(!StringUtil.isEmpty(vo.getPicture2())) {
				picture += vo.getPicture2() + "@@" + this.changeBase64(vo.getPicture2()) + "(X)";
			}
			if(!StringUtil.isEmpty(vo.getPicture3())) {
				picture += vo.getPicture3() + "@@" + this.changeBase64(vo.getPicture3()) + "(X)";
			}
			if(!StringUtil.isEmpty(vo.getPicture4())) {
				picture += vo.getPicture4() + "@@" + this.changeBase64(vo.getPicture4()) + "(X)";
			}
			map.put("picture", picture);
		} else {
			map.put("vo", new WaresInfo());
		}
		return "wares/editwares";
	}
	
	@ResponseBody
	@RequestMapping("queryWares")
	public Map<String, Object> queryWares(HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		int page = this.getPage(request);
		int rows = this.getRows(request);
		Map<String, Object> param = new HashMap<String, Object>();
		List<WaresInfo> list = this.waresService.queryWares(param, page, rows);
		long count = this.waresService.countWares(param);
		result.put("rows", list);
		result.put("total", count);
		return result;
	}
	
	@ResponseBody
	@RequestMapping("saveWares")
	public Map<String, Object> saveWares(HttpServletRequest request, String arr, 
			WaresInfo info, @RequestParam("file") MultipartFile[] files) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		this.deleteImage(info, arr);
		int index = 0;
		if(!StringUtil.isEmpty(arr)) {
			String[] tmp = arr.split(";");
			index = tmp.length;
		}
		for(int i=0; i<files.length; i++) {
			this.saveImageFile(i + index, info, files[i]);
		}
		if(info.getDuration() == null || info.getDuration() == 0) {
			info.setDuration(1);
			info.setDurationUnit(6);
		}
		if(StringUtil.isEmpty(info.getId())) {
			info.setCreator("admin");
			this.waresService.saveWares(info);
			result.put("result", "1");
		} else {
			this.waresService.updateWares(info);
			result.put("result", "2");
		}
		return result;
	}
	
	private String changeBase64(String path) {
		if(!StringUtil.isEmpty(path) && !"null".equals(path)) {
			String str = "data:image/${suffix};base64," + ImageUtil.convertImageToByte(path, StringUtil.getSuffix(path));
			return str.replace("${suffix}", StringUtil.getSuffix(path));
		}
		return "";
	}
	
	private boolean saveImageFile(int index, WaresInfo vo, MultipartFile file) throws Exception {
		if(!file.isEmpty()) {
			byte[] bytes = file.getBytes();
			String sep = System.getProperty("file.separator");
			String tname = file.getOriginalFilename();
			String fileName = UUID.randomUUID().toString().replace("-", "") + "." + StringUtil.getSuffix(tname);
			File dirPath = new File(PATH);
			if(!dirPath.exists()) {
				dirPath.mkdirs();
			}
			File uploadedFile = new File(PATH + sep + fileName);
			FileCopyUtils.copy(bytes, uploadedFile);
			if(StringUtil.isEmpty(vo.getId())) {
				switch (index) {
				case 0:
					vo.setPicture1(PATH + "/" + fileName);
					break;
				case 1:
					vo.setPicture2(PATH + "/" + fileName);
					break;
				case 2:
					vo.setPicture3(PATH + "/" + fileName);
					break;
				case 3:
					vo.setPicture4(PATH + "/" + fileName);
					break;
				}
			} else {
				Map<String, Object> param = new HashMap<String, Object>();
				WaresInfo info = new WaresInfo();
				String id = vo.getId();
				if(!StringUtil.isEmpty(id)) {
					param.put("id", id);
					info = this.waresService.queryWares(param);
				}
				if(info != null && !StringUtil.isEmpty(info.getId())) {
					if(vo.getPicture1() == null) {
						vo.setPicture1(info.getPicture1());
					}
					if(vo.getPicture2() == null) {
						vo.setPicture2(info.getPicture2());
					}
					if(vo.getPicture3() == null) {
						vo.setPicture3(info.getPicture3());
					}
					if(vo.getPicture4() == null) {
						vo.setPicture4(info.getPicture4());
					}
				}
				if(StringUtil.isEmpty(vo.getPicture1())) {
					vo.setPicture1(PATH + "/" + fileName);
				} else if(StringUtil.isEmpty(vo.getPicture2())) {
					vo.setPicture2(PATH + "/" + fileName);
				} else if(StringUtil.isEmpty(vo.getPicture3())) {
					vo.setPicture3(PATH + "/" + fileName);
				} else if(StringUtil.isEmpty(vo.getPicture4())) {
					vo.setPicture4(PATH + "/" + fileName);
				}
			}
		}
		return true;
	}
	
	private boolean deleteImage(String id) {
		Map<String, Object> param = new HashMap<String, Object>();
		WaresInfo info = new WaresInfo();
		if(!StringUtil.isEmpty(id)) {
			param.put("id", id);
			info = this.waresService.queryWares(param);
		}
		if(!StringUtil.isEmpty(info.getPicture1())) {
			File image = new File(info.getPicture1());
			if(image.exists()) {
				image.delete();
			}
		}
		if(!StringUtil.isEmpty(info.getPicture2())) {
			File image = new File(info.getPicture2());
			if(image.exists()) {
				image.delete();
			}
		}
		if(!StringUtil.isEmpty(info.getPicture3())) {
			File image = new File(info.getPicture3());
			if(image.exists()) {
				image.delete();
			}
		}
		if(!StringUtil.isEmpty(info.getPicture4())) {
			File image = new File(info.getPicture4());
			if(image.exists()) {
				image.delete();
			}
		}
		return true;
	}
	
	private boolean deleteImage(WaresInfo vo, String arr) {
		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		if(!StringUtil.isEmpty(arr)) {
			String[] arrs = arr.split(";");
			for(String tmp : arrs) {
				map.put(tmp, 1);
			}
		}
		WaresInfo info = new WaresInfo();
		String id = vo.getId();
		if(!StringUtil.isEmpty(id)) {
			param.put("id", id);
			info = this.waresService.queryWares(param);
		}
		if(!StringUtil.isEmpty(info.getPicture1()) && !map.containsKey(info.getPicture1())) {
			File image = new File(info.getPicture1());
			if(image.exists()) {
				image.delete();
			}
			vo.setPicture1("");
		}
		if(!StringUtil.isEmpty(info.getPicture2()) && !map.containsKey(info.getPicture2())) {
			File image = new File(info.getPicture2());
			if(image.exists()) {
				image.delete();
			}
			vo.setPicture2("");
		}
		if(!StringUtil.isEmpty(info.getPicture3()) && !map.containsKey(info.getPicture3())) {
			File image = new File(info.getPicture3());
			if(image.exists()) {
				image.delete();
			}
			vo.setPicture3("");
		}
		if(!StringUtil.isEmpty(info.getPicture4()) && !map.containsKey(info.getPicture4())) {
			File image = new File(info.getPicture4());
			if(image.exists()) {
				image.delete();
			}
			vo.setPicture4("");
		}
		return true;
	}
	
	@ResponseBody
	@RequestMapping("deleteWares")
	public Map<String, Object> deleteWares(String ids) {
		Map<String, Object> result = new HashMap<String, Object>();
		if(!StringUtil.isEmpty(ids)) {
			List<String> _ids = Arrays.asList(ids.split(","));
			for(String id : _ids) {
				this.deleteImage(id);
			}
			this.waresService.deleteWares(_ids);
			result.put("msg", "OK");
		} else {
			result.put("msg", "FALSE");
		}
		return result;
	}
	
	@RequestMapping("seewares2users")
	public String seewares2users(String uid, ModelMap map) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("uid", uid);
		Map<String, Object> result = this.waresService.queryWares2User(param);
		map.put("result", result);
		return "wares/wares2users";
	}
	
	@ResponseBody
	@RequestMapping("queryWares2Users")
	public Map<String, Object> queryWares2Users(HttpServletRequest request, String wid) {
		Map<String, Object> result = new HashMap<String, Object>();
		int page = this.getPage(request);
		int rows = this.getRows(request);
		if(!StringUtils.isBlank(wid)) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("wid", wid);
			List<Map<String, Object>> list = this.waresService.queryWares2Users(param, page, rows);
			long count = this.waresService.countWares2Users(param);
			result.put("rows", list);
			result.put("total", count);
		} else {
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			long count = 0L;
			result.put("rows", list);
			result.put("total", count);
		}
		return result;
	}

}
